import Http from '../http';

/**
 * 上传响应接口
 */
export interface UploadResponse {
  url: string;
  filename: string;
  originalname: string;
  size: number;
  mimetype: string;
}

/**
 * 多文件上传响应接口
 */
export interface MultipleUploadResponse {
  files: UploadResponse[];
  count: number;
}

/**
 * 上传配置信息接口
 */
export interface UploadConfig {
  maxFileSize: number;
  maxFiles: number;
  allowedTypes: string[];
  allowedExtensions: string[];
}

/**
 * 图片上传API
 */
export class UploadApi {
  /**
   * 上传单张图片
   * @param file 图片文件
   * @returns Promise<UploadResponse>
   */
  static uploadImage(file: File): Promise<UploadResponse> {
    const formData = new FormData();
    formData.append('image', file);

    return Http.post('/api/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }

  /**
   * 上传多张图片
   * @param files 图片文件数组
   * @returns Promise<UploadResponse>
   */
  static uploadMultipleImages(files: File[]): Promise<UploadResponse> {
    const formData = new FormData();
    files.forEach((file, index) => {
      formData.append(`images`, file);
    });

    return Http.post('/api/upload/images', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }

  /**
   * 上传视频文件
   * @param file 视频文件
   * @returns Promise<UploadResponse>
   */
  static uploadVideo(file: File): Promise<UploadResponse> {
    const formData = new FormData();
    formData.append('video', file);

    return Http.post('/api/upload/video', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }

  /**
   * 删除上传的文件
   * @param filename 文件名
   * @returns Promise<void>
   */
  static deleteFile(filename: string): Promise<void> {
    return Http.delete('/api/upload/delete', {
      data: { filename }
    });
  }

  /**
   * 获取上传配置信息
   * @returns Promise<UploadConfig>
   */
  static getUploadConfig(): Promise<UploadConfig> {
    return Http.get('/api/upload/info');
  }

  /**
   * 验证文件类型
   * @param file 文件对象
   * @param allowedTypes 允许的文件类型数组
   * @returns boolean
   */
  static validateFileType(file: File, allowedTypes?: string[]): boolean {
    const defaultAllowedTypes = [
      'image/jpeg',
      'image/jpg', 
      'image/png',
      'image/gif',
      'image/webp'
    ];
    
    const types = allowedTypes || defaultAllowedTypes;
    return types.includes(file.type);
  }

  /**
   * 验证文件大小
   * @param file 文件对象
   * @param maxSize 最大文件大小（字节），默认10MB
   * @returns boolean
   */
  static validateFileSize(file: File, maxSize: number = 10 * 1024 * 1024): boolean {
    return file.size <= maxSize;
  }

  /**
   * 格式化文件大小
   * @param bytes 字节数
   * @returns string
   */
  static formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  /**
   * 获取文件预览URL
   * @param file 文件对象
   * @returns string
   */
  static getFilePreviewUrl(file: File): string {
    return URL.createObjectURL(file);
  }

  /**
   * 释放文件预览URL
   * @param url 预览URL
   */
  static revokeFilePreviewUrl(url: string): void {
    URL.revokeObjectURL(url);
  }

  /**
   * 批量验证文件
   * @param files 文件数组
   * @param config 验证配置
   * @returns { valid: File[], invalid: { file: File, reason: string }[] }
   */
  static validateFiles(
    files: File[], 
    config?: {
      maxFileSize?: number;
      maxFiles?: number;
      allowedTypes?: string[];
    }
  ): {
    valid: File[];
    invalid: { file: File; reason: string }[];
  } {
    const {
      maxFileSize = 10 * 1024 * 1024, // 10MB
      maxFiles = 10,
      allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
    } = config || {};

    const valid: File[] = [];
    const invalid: { file: File; reason: string }[] = [];

    // 检查文件数量
    if (files.length > maxFiles) {
      files.slice(maxFiles).forEach(file => {
        invalid.push({ file, reason: `文件数量超出限制，最多只能上传${maxFiles}个文件` });
      });
      files = files.slice(0, maxFiles);
    }

    files.forEach(file => {
      // 检查文件类型
      if (!this.validateFileType(file, allowedTypes)) {
        invalid.push({ 
          file, 
          reason: `不支持的文件类型: ${file.type}。支持的类型: ${allowedTypes.join(', ')}` 
        });
        return;
      }

      // 检查文件大小
      if (!this.validateFileSize(file, maxFileSize)) {
        invalid.push({ 
          file, 
          reason: `文件大小超出限制: ${this.formatFileSize(file.size)}。最大允许: ${this.formatFileSize(maxFileSize)}` 
        });
        return;
      }

      valid.push(file);
    });

    return { valid, invalid };
  }
}